from rest_framework import serializers

from .models import Post, Category


# class PopularPostSerializer(serializers.HyperlinkedModelSerializer):
class PopularPostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ('slug', 'num_views')


# 序列化数据给文章列表和详情页面
class PostSerializer(serializers.ModelSerializer):
    # 显示标签列表和分类名字，而不是默认的id
    tags = serializers.SerializerMethodField()
    category = serializers.CharField(source='category.name')
    # img_url = serializers.URLField(source='img.url')

    class Meta:
        model = Post
        fields = (
            'id',
            'slug',
            'title',
            'subtitle',
            'img_path',
            'content',
            'excerpt',
            # 'created',
            'pub_date',  # 传递较好的时间格式到前端2020.02.23 20:32
            'category',
            'tags',
            'num_views',
        )
        # depth = 1

    # # 对应与上面的SerializerMethodField,获取标签列表
    def get_tags(self, obj):
        return [t.name for t in obj.tags.all()]


# 类别列表
class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('name',)


class PostsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ('title', 'pub_date', 'slug')

